package com.example.furniture.controller;

import com.example.furniture.entity.User;
import com.example.furniture.service.UserService;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.util.List;

/**
 * 用户管理控制器
 * 提供用户的增删改查功能
 * 
 * @author 家具商城系统
 * @version 1.0
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/users")
@CrossOrigin(origins = "*") // 允许跨域访问，用于前端调用
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    private final UserService userService;

    /**
     * 构造函数，注入用户服务
     * 
     * @param userService 用户服务实例
     */
    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 获取所有用户列表
     * 
     * @return 用户列表
     */
    @GetMapping
    public ResponseEntity<List<User>> list() {
        try {
            logger.info("获取所有用户列表");
            List<User> users = userService.listAll();
            return ResponseEntity.ok(users);
        } catch (Exception e) {
            logger.error("获取用户列表失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 根据ID获取用户信息
     * 
     * @param id 用户ID
     * @return 用户信息，如果不存在返回404
     */
    @GetMapping("/{id}")
    public ResponseEntity<User> get(@PathVariable("id") Long id) {
        try {
            logger.info("获取用户信息，ID: {}", id);
            User user = userService.getById(id);
            if (user == null) {
                logger.warn("用户不存在，ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(user);
        } catch (Exception e) {
            logger.error("获取用户信息失败，ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 创建新用户
     * 
     * @param user 用户信息
     * @return 创建的用户信息
     */
    @PostMapping
    public ResponseEntity<User> create(@Valid @RequestBody User user) {
        try {
            logger.info("创建新用户: {}", user.getUsername());
            User saved = userService.create(user);
            logger.info("用户创建成功，ID: {}", saved.getId());
            return ResponseEntity.created(URI.create("/users/" + saved.getId())).body(saved);
        } catch (Exception e) {
            logger.error("创建用户失败: {}", user.getUsername(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 更新用户信息
     * 
     * @param id 用户ID
     * @param user 更新的用户信息
     * @return 更新后的用户信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<User> update(@PathVariable("id") Long id, @Valid @RequestBody User user) {
        try {
            logger.info("更新用户信息，ID: {}", id);
            User existingUser = userService.getById(id);
            if (existingUser == null) {
                logger.warn("用户不存在，无法更新，ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            User updated = userService.update(id, user);
            logger.info("用户更新成功，ID: {}", id);
            return ResponseEntity.ok(updated);
        } catch (Exception e) {
            logger.error("更新用户失败，ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 删除用户
     * 
     * @param id 用户ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable("id") Long id) {
        try {
            logger.info("删除用户，ID: {}", id);
            User existingUser = userService.getById(id);
            if (existingUser == null) {
                logger.warn("用户不存在，无法删除，ID: {}", id);
                return ResponseEntity.notFound().build();
            }
            userService.delete(id);
            logger.info("用户删除成功，ID: {}", id);
            return ResponseEntity.noContent().build();
        } catch (Exception e) {
            logger.error("删除用户失败，ID: {}", id, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}


